package top.lyc829.zzl_android.ui.profile.user_dtc.travels;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.jetbrains.annotations.NotNull;

import top.lyc829.zzl_android.databinding.FragmentUserTravelsBinding;
import top.lyc829.zzl_android.logic.bean.TravelsSimpleBean;
import top.lyc829.zzl_android.logic.util.PageInfo;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.ui.thing.travel_detail.TravelDetailActivity;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserTravelsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserTravelsFragment extends Fragment {


    private UserTravelsViewModel mviewModel;
    UserTravelsAdapter adapter;
    FragmentUserTravelsBinding binding;
    private int otherUserId = -1;

    // TODO: Rename and change types and number of parameters
    public static UserTravelsFragment newInstance() {
        return new UserTravelsFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentUserTravelsBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mviewModel=new ViewModelProvider(this).get(UserTravelsViewModel.class);

        LiveEventBus
                .get("logout", Integer.class)
                .observeSticky(this, new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (integer.equals(1)) {
                            //Utils.Sout("接收到注销消息");
                            mviewModel.getUserTravelsLiveData().setValue(null);
                        }
                    }
                });

        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        binding.userTravelsRecyclerview.setLayoutManager(staggeredGridLayoutManager);
        adapter=new UserTravelsAdapter();
        adapter.setAnimationEnable(true);   // recyclerview加载动画
        binding.userTravelsRecyclerview.setAdapter(adapter);

        binding.userTravelsRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                staggeredGridLayoutManager.invalidateSpanAssignments();//这行主要解决了当加载更多数据时，底部需要重绘，否则布局可能衔接不上。
            }
        });

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent intent=new Intent(getActivity(),  TravelDetailActivity.class);
                intent.putExtra("travel_id", ((TravelsSimpleBean)adapter.getData().get(position)).getId());
                startActivity(intent);
            }
        });


        request();
        binding.swipeLayout.setRefreshing(true);
        //refresh();
        initRefreshLayout();

        observe();
    }

//    private void initLoadMore() {
//        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
//            @Override
//            public void onLoadMore() {
//                request();
//            }
//        });
//        adapter.getLoadMoreModule().setAutoLoadMore(true);
//        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
//        adapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
//    }
    private void initRefreshLayout() {
        binding.swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        binding.swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }
    /**
     * 刷新
     */
    private void refresh() {
        // 这里的作用是防止下拉刷新的时候还可以上拉加载
        adapter.getLoadMoreModule().setEnableLoadMore(false);
        // 下拉刷新，需要重置页数
        request();
    }
    //这里的user_id要怎么传过来的
    private void request() {
        if(otherUserId==-1)
        {
            mviewModel.getUserTravelsList(Utils.getUserId());
        }
       else
        {
            mviewModel.getUserTravelsList(otherUserId);
        }
    }


    private void observe(){
        mviewModel.getUserTravelsLiveData().observe(getViewLifecycleOwner(), TravelsSimpleBean->
        {
            binding.swipeLayout.setRefreshing(false);
            adapter.setList(TravelsSimpleBean);
//            adapter.getLoadMoreModule().setEnableLoadMore(true);
//            if(pageInfo.isFirstPage()){
//                adapter.setList(TravelsSimpleBean);
//            }
//            else
//            {
//                adapter.addData(TravelsSimpleBean);
//            }
//            pageInfo.nextPage();
//            // 加载完成，等待下一次加载
//            adapter.getLoadMoreModule().loadMoreComplete();
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    public void setotherUserId(int otherUserId) {
        this.otherUserId = otherUserId;
    }
}